/*
* configdlg.cpp - This file is the part of the wp-notifier.(code name "luan luan")
* Copyright (C) 2010 Dean Lee <deanlee3@gmail.com>, http://www.deanlee.cn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
* 
* Acknowledgements:
*   <> Many thanks to all of you, who have encouraged me to update my articles
*     and code, and who sent in bug reports and fixes.
* 
*/
#include <QFile>
#include <QTextStream>
#include "configdlg.h"
#include "commentsmodel.h"
#include "blogwizard.h"
#include "common.h"
#include "mainwin.h"
Option s_opt;

ConfigDlg* ConfigDlg::s_instance = NULL;

ConfigDlg* ConfigDlg::showConfigDlg()
{
	if (!s_instance) {
		s_instance = new ConfigDlg();
	}
	else {
		bringToFront(s_instance);
	}
	return s_instance;
}

Option::Option()
{
	Init();
}
void Option::Init()
{
	m_autoStart = true;
	m_pageSize = 16;
	m_checkInterval = 5 * 60 * 1000;
	m_showFullComments = true;
	m_winSize.setWidth(252);
	m_winSize.setHeight(444);
}

//bool Option::load()
//{
//	bool result = false;
//	QFile file(homeDir() + "/config.xml");
//	if (file.open(QIODevice::ReadOnly)) {
//		QDomDocument doc;
//		result = doc.setContent(&file);
//		file.close();
//		if (result) {
//			s_opt.fromXml(doc.documentElement());
//		}
//	}
//	return result;
//}

//bool Option::save()
//{
//	bool result = false;
//	QFile file(homeDir() + "/config.xml");
//	if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
//		QDomDocument doc;
//		QDomElement el = s_opt.toXml(&doc);
//		doc.appendChild(el);
//		QTextStream text;
//		text.setDevice(&file);
//		text.setCodec("UTF-8");
//		text << doc.toString();
//		result = file.error() == QFile::NoError;
//		file.close();
//	}
//	return result;
//}

void Option::fromXml(const QDomElement& el)
{
	readBoolEntry(el, "autostart", &m_autoStart);
	readNumEntry(el, "pagesize", &m_pageSize);
//	readNumEntry(el, "lastcommentid", &m_lastCommentId);
	readSizeEntry(el, "windowsize", &m_winSize);
	bool found;
	//QDomElement blogs = findSubTag(el, "blogs", &found);
	//if (found) {
	//	for(QDomNode n = blogs.firstChild(); !n.isNull(); n = n.nextSibling()) {
	//		QDomElement i = n.toElement();
	//		if(i.isNull())
	//			continue;

	//		if(i.tagName() == "blog") {
	//			Blog* blog = new Blog();
	//			blog->fromXml(i);
	//			m_blogs << blog;
	//		}
	//	}
	//}
}
//QDomElement textTag(QDomDocument &doc, const QString &name, QSize &s)

QDomElement Option::toXml(QDomDocument *doc)const
{
	QDomElement e = doc->createElement("option");
	e.appendChild( textTag(*doc, "autostart", m_autoStart? "true" : "false"));
	e.appendChild( textTag(*doc, "pagesize", QString::number(m_pageSize)));
	e.appendChild( textTag(*doc, "windowsize", (QSize&)m_winSize));
	//QDomElement blogs = doc->createElement("blogs");
	/*foreach(Blog* blog, m_blogs) {
		blogs.appendChild(blog->toXml(doc));
	}*/
	//e.appendChild(blogs);
	return e;
}

ConfigDlg::ConfigDlg(QWidget* parent) : QDialog(parent)
{
	setAttribute(Qt::WA_DeleteOnClose);
	ui_.setupUi(this);
	ui_.sp_check_interval->setValue(s_opt.m_checkInterval / (60 * 1000));
	ui_.cb_autostartup->setChecked(s_opt.m_autoStart);

	connect(ui_.lw_blogs->model(), SIGNAL(rowsInserted(const QModelIndex &, int, int)), SLOT(rowsChanged()));
	connect(ui_.lw_blogs->model(), SIGNAL(rowsRemoved(const QModelIndex &, int, int)), SLOT(rowsChanged()));
	foreach(CommentsModel* m, MainWindow::instance()->models()) {
		QListWidgetItem* item = new QListWidgetItem(m->blog().name());
		//item->setCheckState(Qt::Checked);
		item->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled /*| Qt::ItemIsUserCheckable*/);

		ui_.lw_blogs->addItem(item);
	}
	ui_.lw_blogs->setCurrentRow(0);

	connect(ui_.lw_blogs, SIGNAL(currentRowChanged(int)), SLOT(currentRowChanged(int)));
	connect(ui_.pb_edit, SIGNAL(clicked()), SLOT(editAccount()));
	connect(ui_.pb_add, SIGNAL(clicked()), SLOT(addAccount()));
	connect(ui_.pb_delete, SIGNAL(clicked()), SLOT(deleteAccount()));
	connect(ui_.pb_view, SIGNAL(clicked()), SLOT(viewAccount()));
	connect(ui_.buttonBox, SIGNAL(clicked(QAbstractButton *)), SLOT(clicked(QAbstractButton *)));
	show();
}

ConfigDlg::~ConfigDlg()
{
	s_instance = NULL;
}

void ConfigDlg::rowsChanged()
{
	if (ui_.lw_blogs->count() > 1 ) {
		ui_.pb_delete->setEnabled(true);
	}
	else {
		ui_.pb_delete->setEnabled(false);
	}
}

void ConfigDlg::currentRowChanged(int /*currentRow*/)
{
	ui_.pb_delete->setEnabled(true);
}

void ConfigDlg::manageAccount(const Blog* blog)
{
	BlogWizard wizard(blog);
	if (QDialog::Accepted == wizard.exec()) {
		foreach(Blog blog, wizard.blogs()) {
			bool found = false;
			foreach(CommentsModel* m, MainWindow::instance()->models()) {
				if (m->blog().id() == blog.id() && m->blog().xmlrpcUrl() == blog.xmlrpcUrl()) {
					//*((BlogData*)oldBlog) = *blog;
					m->setBlog(blog);
					found = true;
					//emit accountUpdated(oldBlog);
					break;
				}
			}
			if (!found) {
				CommentsModel* model = new CommentsModel();
				model->setBlog(blog);
				QListWidgetItem* item = new QListWidgetItem(blog.name());
				//item->setCheckState(Qt::Checked);
				item->setFlags(Qt::ItemIsEditable | Qt::ItemIsSelectable | Qt::ItemIsEnabled /*| Qt::ItemIsUserCheckable*/);
				ui_.lw_blogs->addItem(item);
				//emit accountAdded(b);
				//s_opt.m_blogs << b;
			}
		}
		//s_opt.save();
		MainWindow::instance()->saveOptions();
	}
}

void ConfigDlg::editAccount()
{
	//manageAccount(s_opt.m_blogs.at(ui_.lw_blogs->currentRow()));
}

void ConfigDlg::addAccount()
{
	manageAccount(NULL);
}

void ConfigDlg::deleteAccount()
{
	/*Blog* blog = s_opt.m_blogs.at(ui_.lw_blogs->currentRow());
	emit accountDeleted(blog);
	s_opt.m_blogs.removeAt(ui_.lw_blogs->currentRow());
	delete blog;
	QListWidgetItem* item = ui_.lw_blogs->takeItem(ui_.lw_blogs->currentRow());
	delete item;
	s_opt.save();*/
}

void ConfigDlg::viewAccount()
{
}

void ConfigDlg::done ( int r )
{
	QDialog::done(r);
}

void ConfigDlg::clicked(QAbstractButton * btn)
{
	/*if (btn == ui_.buttonBox->button(QDialogButtonBox::Ok)) {
		for (int i = 0; i < ui_.lw_blogs->count(); ++i) {
			s_opt.m_blogs.at(i)->m_blog_name = ui_.lw_blogs->item(i)->text();
		}
		s_opt.m_checkInterval = ui_.sp_check_interval->value() * (60 * 1000);
		s_opt.m_autoStart = ui_.cb_autostartup->isChecked();
		setStartup(s_opt.m_autoStart);
		s_opt.save();
		accept();

	}
	else if (btn == ui_.buttonBox->button(QDialogButtonBox::Cancel)) {
		reject();

	}*/
}

